package com.cqsd.ioc.util;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author caseycheng
 * @date 2023/3/19-13:13
 **/
final public class RunTimeUtil {
    private static final Map<String,Thread> THREAD_MAP =new HashMap<>();

    public static void addShutdownHook(Runnable run,String name){
        //noinspection AlibabaAvoidManuallyCreateThread
        final Thread shutdownThread = new Thread(run, name);
        THREAD_MAP.put(name,shutdownThread);
        Runtime.getRuntime().addShutdownHook(shutdownThread);
    }

    public static void removeShutdownHook(String name){
        Objects.requireNonNull(name);
        //清除已使用的线程，虽然不一定会有这种场景。活着的线程留下，已使用的线程离开
        MapUtil.removeIf(THREAD_MAP,(k, v)->v.isAlive());
        final var thread = THREAD_MAP.get(name);
        Objects.requireNonNull(thread,String.format("未找到%s所对应的线程",name));
        Runtime.getRuntime().removeShutdownHook(thread);
    }


}
